package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;

public class UserServiceImpl implements UserService {
    @Override
    public PageInfo findByPage(int currentPage) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        PageHelper.startPage(currentPage,5);
        List<User> list = mapper.findAll();
        PageInfo info = new PageInfo(list);
        sqlSession.close();
        return info;
    }

    @Override
    public void update(User user) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.update(user);
        sqlSession.close();
    }

    @Override
    public void delete(String userId) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.delete(userId);
        sqlSession.close();
    }

    @Override
    public void add(User user) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        String id = UUID.randomUUID().toString();
        user.setUserId(id);
        mapper.add(user);
        sqlSession.close();
    }

    @Override
    public User findByUsernameAndPassword(String username, String password) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.findByUsernameAndPassword(username,password);
        sqlSession.close();
        return user;
    }
}
